<template>
  <div class="overview-container">
    <!-- 顶部导航 -->
    <AppHeader />

    <!-- 主内容区 -->
    <div class="overview-content">
      <!-- 统计卡片区 -->
      <div class="stat-cards">
        <StatCard
          title="总检测数"
          :value="dataStore.statisticsData.total"
          icon="DataAnalysis"
          trend="up"
          :trend-value="`↑ ${dataStore.statisticsData.trends?.total || 0}%`"
          color="#409EFF"
        />
        <StatCard
          title="今日检测"
          :value="dataStore.statisticsData.today"
          icon="Calendar"
          trend="up"
          :trend-value="`↑ ${dataStore.statisticsData.trends?.today || 0}%`"
          color="#67C23A"
        />
        <StatCard
          title="本周检测"
          :value="dataStore.statisticsData.week"
          icon="TrendCharts"
          trend="up"
          :trend-value="`↑ ${dataStore.statisticsData.trends?.week || 0}%`"
          color="#E6A23C"
        />
        <StatCard
          title="本月检测"
          :value="dataStore.statisticsData.month"
          icon="PieChart"
          trend="up"
          :trend-value="`↑ ${dataStore.statisticsData.trends?.month || 0}%`"
          color="#F56C6C"
        />
      </div>

      <!-- 图表区域 -->
      <div class="charts-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span>体质成分分布</span>
                  <el-tag size="small">饼图</el-tag>
                </div>
              </template>
              <div class="chart-placeholder">
                <el-icon :size="60" color="#909399"><DataAnalysis /></el-icon>
                <p>图表功能开发中...</p>
              </div>
            </el-card>
          </el-col>

          <el-col :span="12">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span>月度趋势分析</span>
                  <el-tag size="small" type="success">折线图</el-tag>
                </div>
              </template>
              <div class="chart-placeholder">
                <el-icon :size="60" color="#909399"><TrendCharts /></el-icon>
                <p>图表功能开发中...</p>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="24">
            <el-card class="chart-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <span>患者体质成分对比分析</span>
                  <el-tag size="small" type="warning">柱状图</el-tag>
                </div>
              </template>
              <div class="chart-placeholder">
                <el-icon :size="60" color="#909399"><Histogram /></el-icon>
                <p>图表功能开发中...</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 数据列表区 -->
      <div class="data-table-section">
        <el-card class="table-card" shadow="hover">
          <template #header>
            <div class="table-header">
              <span class="header-title">患者数据列表</span>
              <div class="header-actions">
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="搜索患者ID或姓名"
                  :prefix-icon="Search"
                  clearable
                  style="width: 200px; margin-right: 12px;"
                  @input="handleSearch"
                />
                <el-select
                  v-model="searchForm.scanType"
                  placeholder="扫描类型"
                  clearable
                  style="width: 120px; margin-right: 12px;"
                  @change="handleSearch"
                >
                  <el-option label="胸部CT" value="chest" />
                  <el-option label="腹部CT" value="abdomen" />
                </el-select>
                <el-date-picker
                  v-model="searchForm.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 240px; margin-right: 12px;"
                  @change="handleSearch"
                />
                <el-button type="primary" :icon="Download" @click="handleExport">
                  导出Excel
                </el-button>
              </div>
            </div>
          </template>

          <el-table
            :data="dataStore.paginatedList"
            :loading="dataStore.loading"
            stripe
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="患者ID" width="120" />
            <el-table-column prop="name" label="姓名" width="100" />
            <el-table-column prop="gender" label="性别" width="80" />
            <el-table-column prop="age" label="年龄" width="80" />
            <el-table-column prop="date" label="检测日期" width="120" />
            <el-table-column prop="scanType" label="扫描类型" width="100">
              <template #default="{ row }">
                <el-tag :type="row.scanType === '胸部CT' ? 'primary' : 'success'" size="small">
                  {{ row.scanType }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="vertebralLevel" label="椎体层面" width="100" />
            <el-table-column prop="subcutaneousFat" label="皮下脂肪(cm²)" width="130" align="right" />
            <el-table-column prop="visceralFat" label="内脏脂肪(cm²)" width="130" align="right" />
            <el-table-column prop="skeletalMuscle" label="骨骼肌(cm²)" width="120" align="right" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag
                  :type="getStatusType(row.status)"
                  size="small"
                >
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" :icon="View" @click="handleView(row)">
                  查看
                </el-button>
                <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="dataStore.currentPage"
              v-model:page-size="dataStore.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="dataStore.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Download, View, Delete, DataAnalysis, TrendCharts, Histogram } from '@element-plus/icons-vue'
import AppHeader from '@/components/layout/AppHeader.vue'
import StatCard from '@/components/business/StatCard.vue'
import { useDataStore } from '@/stores/data'

const dataStore = useDataStore()

// 搜索表单
const searchForm = reactive({
  keyword: '',
  scanType: '',
  dateRange: []
})

// 选中的数据
const selectedRows = ref([])

// 图表数据
const compositionChartData = ref({
  data: [
    { value: 45, name: '皮下脂肪', itemStyle: { color: '#FFD700' } },
    { value: 30, name: '内脏脂肪', itemStyle: { color: '#FF6B6B' } },
    { value: 25, name: '骨骼肌', itemStyle: { color: '#4ECDC4' } }
  ]
})

const trendChartData = ref({
  xData: ['1月', '2月', '3月', '4月', '5月', '6月'],
  series: [
    {
      name: '检测数量',
      data: [120, 132, 101, 134, 90, 156],
      itemStyle: { color: '#409EFF' }
    }
  ]
})

const comparisonChartData = ref({
  xData: ['P001', 'P002', 'P003', 'P004', 'P005', 'P006'],
  series: [
    {
      name: '皮下脂肪',
      data: [120, 132, 101, 134, 90, 156],
      itemStyle: { color: '#FFD700' }
    },
    {
      name: '内脏脂肪',
      data: [80, 95, 70, 89, 65, 98],
      itemStyle: { color: '#FF6B6B' }
    },
    {
      name: '骨骼肌',
      data: [140, 150, 130, 145, 120, 160],
      itemStyle: { color: '#4ECDC4' }
    }
  ]
})

// Methods
const handleSearch = () => {
  // 实际项目中应该调用API进行搜索
  dataStore.fetchPatientList(searchForm)
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleView = (row) => {
  ElMessage.info(`查看患者 ${row.name} 的详细信息`)
  // 实际项目中应该跳转到详情页或打开详情弹窗
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除患者 ${row.name} 的数据吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    dataStore.deletePatient(row.id)
    ElMessage.success('删除成功')
  }).catch(() => {
    // 取消删除
  })
}

const handleExport = () => {
  const ids = selectedRows.value.map(row => row.id)
  dataStore.exportData(ids.length > 0 ? ids : null)
  ElMessage.success('正在导出数据...')
}

const handleSizeChange = (size) => {
  dataStore.setPageSize(size)
}

const handlePageChange = (page) => {
  dataStore.setCurrentPage(page)
}

const getStatusType = (status) => {
  const statusMap = {
    '已完成': 'success',
    '分析中': 'warning',
    '待分析': 'info'
  }
  return statusMap[status] || 'info'
}

// Lifecycle
onMounted(() => {
  dataStore.fetchStatistics()
  dataStore.fetchPatientList()
})
</script>

<style lang="scss" scoped>
.overview-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;

  .overview-content {
    flex: 1;
    overflow-y: auto;
    padding: 20px;

    // 统计卡片区
    .stat-cards {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 20px;
      margin-bottom: 20px;
    }

    // 图表区域
    .charts-section {
      margin-bottom: 20px;

      .chart-card {
        border-radius: 12px;

        :deep(.el-card__header) {
          padding: 16px 20px;
          border-bottom: 1px solid #ebeef5;
        }

        .card-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }

        :deep(.el-card__body) {
          padding: 20px;
        }

        .chart-placeholder {
          height: 300px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          gap: 16px;
          color: #909399;
          
          p {
            font-size: 14px;
            margin: 0;
          }
        }
      }
    }

    // 数据列表区
    .data-table-section {
      .table-card {
        border-radius: 12px;

        :deep(.el-card__header) {
          padding: 16px 20px;
          border-bottom: 1px solid #ebeef5;
        }

        .table-header {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .header-title {
            font-size: 16px;
            font-weight: 600;
            color: #303133;
          }

          .header-actions {
            display: flex;
            align-items: center;
          }
        }

        :deep(.el-card__body) {
          padding: 0;
        }

        .pagination-wrapper {
          display: flex;
          justify-content: center;
          padding: 20px;
          border-top: 1px solid #ebeef5;
        }
      }
    }
  }
}

// 响应式
@media (max-width: 1600px) {
  .overview-content {
    .stat-cards {
      grid-template-columns: repeat(2, 1fr);
    }
  }
}

@media (max-width: 1024px) {
  .overview-content {
    .stat-cards {
      grid-template-columns: repeat(1, 1fr);
    }

    .charts-section {
      :deep(.el-col) {
        width: 100%;
        margin-bottom: 20px;
      }
    }

    .table-header {
      flex-direction: column;
      align-items: flex-start !important;
      gap: 12px;

      .header-actions {
        width: 100%;
        flex-wrap: wrap;
      }
    }
  }
}
</style>

